from rest_framework import permissions

from .utils.group_info import get_all_group_info

from .models.geninfo import GeneralInfo

from rest_framework.exceptions import PermissionDenied as permDenied


class CheckOptionPermission(permissions.BasePermission):

    def has_permission(self, request, view):

        all_perm = request.user.get_all_permissions()
        own_perm = [perm for perm in all_perm if perm.startswith('prj001')]

        if not own_perm:
            return False
        return True

    def has_object_permission(self, request, view, obj):
        if request.user.has_perm('prj001.prj001_all'):
            return True
        elif request.user.has_perm('prj001.prj001_operation'):
            if request.method in permissions.SAFE_METHODS:
                return True
            else:
                return obj.owner == request.user
        else:
            return False


class MobileClientPermission(permissions.BasePermission):
    ''' for mobile entering person '''

    def has_permission(self, request, view):
        if request.method not in permissions.SAFE_METHODS:
            if request.user.has_perm('prj001.prj001_patient'):
                return True
            else:
                return False
        # return True


#
def get_queryset_perm(sf, obj=None, is_not_info=None):
    ''' check perm & return data of corresponding'''
    user = sf.request.user
    is_self = user.has_perm('prj001.prj001_operation')
    is_all = user.has_perm('prj001.prj001_all')

    if is_all:
        return get_all_group_info(obj=obj, is_not_info=is_not_info)
    elif is_self:
        if is_not_info and obj:
            return obj.objects.filter(owner=user).order_by('-pk')

        if obj:
            return obj.objects.filter(owner=user).order_by('-serial')
        return GeneralInfo.objects.filter(owner=user).order_by('-serial')
    else:
        raise permDenied(detail={'msg': '对不起, 您没有查看数据的权限'})


def cur_info_perm(sf):
    ''' for info table's checked status '''
    cur_obj = sf.get_object()

    if cur_obj.is_checked == '审核通过':
        raise permDenied(detail={'msg': '此条信息已经审核通过, 请勿操作; 如需修改, 请更改审核状态'})


def cur_other_perm(sf):
    ''' for other table's checked status '''
    cur_obj = sf.get_object()

    if cur_obj.person.is_checked == '审核通过':
        raise permDenied(detail={'msg': '此条信息已经审核通过, 请勿操作; 如需修改, 请更改审核状态'})
